﻿var refreshGirdData; // 更新数据
var companyId = '';
var ztId = '';
var kjnd = '';
var kjkm = [];
var userdefault = {};
var params={};

var bootstrap = function ($, learun) {

    var pageWidth = 1024;
    var hiprintTemplate_index = null;
    var hiprintTemplate_content = null;

    "use strict";
    var page = {
        init: function () {
            userdefault = learun.clientdata.get(['usersetting']);
            //初始化打印插件
            hiprint.init();
            pageWidth = ($('.lr-layout-grid').width());
            $(".prevViewDiv2").height($(window).height() - 120);
            page.initGrid();
            page.bind();


        },
        bind: function () {
            $('#multiple_condition_query').lrMultipleQuery(function (queryJson) {
                // 调用后台查询
                // queryJson 查询条件
                page.search(queryJson);

            }, 250, 1000);
            $('#pzrqMonth').lrselect({
                type: 'default',
                // 展开最大高度
                maxHeight: 300,
                placeholder: '月份',
                data: [
                    {'id': '01', 'text': '01'},
                    {'id': '02', 'text': '02'},
                    {'id': '03', 'text': '03'},
                    {'id': '04', 'text': '04'},
                    {'id': '05', 'text': '05'},
                    {'id': '06', 'text': '06'},
                    {'id': '07', 'text': '07'},
                    {'id': '08', 'text': '08'},
                    {'id': '09', 'text': '09'},
                    {'id': '10', 'text': '10'},
                    {'id': '11', 'text': '11'},
                    {'id': '12', 'text': '12'}
                ],
                select: function (item) {
                    if (!item || item.id == '-1') {
                        var beginDate = kjnd + "-01-01";
                        var day = new Date(kjnd, 12, 0);
                        var endDate = kjnd + "-" + 12 + "-" + day.getDate();
                        $("#pzrqStart").val(beginDate);
                        $("#pzrqEnd").val(endDate);
                    } else {
                        var kjqj = item.id;
                        var beginDate = kjnd + "-" + kjqj + "-01";
                        var day = new Date(kjnd, kjqj, 0);
                        var endDate = kjnd + "-" + kjqj + "-" + day.getDate();
                        $("#pzrqStart").val(beginDate);
                        $("#pzrqEnd").val(endDate);
                    }
                }
            });
            // 公司选择
            $('#company_select').lrselect({
                type: 'tree',
                // placeholder: '请选择机构',
                height: 300,
                maxHeight: 300,
                // 是否允许搜索
                //allowSearch: true,
                select: function (item) {
                    if (item && item.value != '-1') {
                        companyId = item.value;
                    }
                }
            });
            $('#company_select').lrselectRefresh({
                // 访问数据接口地址
                url: config.base_server() + 'companys/tree?access_token=' + config.getToken().access_token,
                // 访问数据接口参数
                param: {parentId: '0'}
            }).lrselectSet(userdefault.companyId);

            // 帐套选择
            $('#zt_select').lrDataItemSelect({
                code: 'ZT', maxHeight: 100,
                select: function (item) {
                    if (!item || item.id == '-1') {
                        ztId = '';
                    } else {
                        page.initPrintTemplete();
                        ztId = item.id;
                        $("#zt_title").html(item.text);
                    }
                }
            }).lrselectSetFirst();

            // 凭证类型
            $('#pzlxCode').lrDataItemSelect({
                code: 'PZLXS', maxHeight: 100,placeholder: "==请选择凭证类型==",
                select: function (item) {

                }
            });

            // 会计年度选择
            $('#kjnd_select').lrDataItemSelect({
                code: 'YEAR', maxHeight: 100, placeholder: "==请选择年份==",
                select: function (item) {
                    if (!item || item.value == '-1') {
                        kjnd = '';
                    } else {
                        kjnd = item.value;

                        var beginDate = kjnd + "-01-01";
                        var day = new Date(kjnd, 12, 0);
                        var endDate = kjnd + "-12-" + day.getDate();
                        $("#pzrqStart").val(beginDate);
                        $("#pzrqEnd").val(endDate);


                        $('#kjkmCodes').lrlayerselect({
                            dataValueId: 'code',
                            dataTextId: 'codeAndName',
                            reset: true,
                            url: config.base_server() + 'kjkms/list?companyId=' + companyId + '&ztId=' + ztId + '&kjnd=' + kjnd + '&status=1' + '&access_token=' + config.getToken().access_token,
                            grid: [
                                {label: '科目', name: 'codeAndName', width: 225, align: 'left'},
                                {
                                    label: "余额方向", name: "yefx", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "借" : "贷";
                                    }
                                },
                                {
                                    label: "项目", name: "isXmHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {
                                    label: "部门", name: "isBmHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {
                                    label: "案件", name: "isAjHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {
                                    label: "票据号", name: "isPjhHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {
                                    label: "支票号", name: "isZphHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {
                                    label: "往来", name: "isWlHs", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "是" : "";
                                    }
                                },
                                {label: '是否明细', name: 'isMx', width: 1, align: 'left', hidden: true},
                                {label: '编号', name: 'code', width: 120, align: 'left', hidden: true},
                                {label: '简称', name: 'simpleName', width: 225, align: 'left', hidden: true}
                            ],
                            select: function (values, texts) {
                                kjkm = values;
                            }
                        });
                    }
                }
            });
            // 查询
            $('#btn_Search').on('click', function () {
                page.search(params);
            });
            // 刷新
            $('#lr_refresh').on('click', function () {
                location.reload();
            });

            //打印预览
            $('#lr_printview').on('click', function () {
                if (!$.isArray(kjkm) || kjkm.length == 0) {
                    learun.alert.warning('请选择科目！');
                    return;
                }
                learun.loading(true, '正在获取数据');

                learun.httpAsync2('GET', config.base_server() + 'reports/slmxzbook?access_token=' + config.getToken().access_token, params, function (res) {
                    learun.loading(false);
                    if (res.resp_code == 200) {
                        var indexSize = 40;
                        var pzflSize = 37;
                        var index = {};
                        index.list = res.data.index.splice(0,indexSize);
                        if(res.data.content.length<=indexSize){
                            indexSize=res.data.content.length;
                        }
                        var itemList = [];
                        for (var i = 0; i < indexSize; i++) {
                            if(res.data.content[i].pzflList.length < pzflSize){
                                pzflSize = res.data.content[i].pzflList.length;
                            }
                            for (var j = 0; j < pzflSize; j++) {
                                res.data.content[i].pzflList[j].j = $.formatMoney(res.data.content[i].pzflList[j].j, 2);
                                res.data.content[i].pzflList[j].d = $.formatMoney(res.data.content[i].pzflList[j].d, 2);
                                res.data.content[i].pzflList[j].ye = $.formatMoney(res.data.content[i].pzflList[j].ye, 2);
                            }
                            //只预览37条记录
                            res.data.content[i].pzflList = res.data.content[i].pzflList.splice(0,pzflSize);
                            itemList.push(res.data.content[i]);
                        }

                        //多模板打印预览
                        $('#myModal .modal-body .prevViewDiv').html(hiprint.getHtml({templates: [{template: hiprintTemplate_index, data: index, options: {}}, {template: hiprintTemplate_content, data: itemList}]}));
                        $('#printerlist').html(page.createPrintHtml(hiprintTemplate_index.getPrinterList()));
                        $('#myModal').modal('show');

                        $('#A4_printByHtml').click(function () {
                            // hiprintTemplate_index.printByHtml($('#myModal .modal-body .prevViewDiv'));
                            // hiprintTemplate_content.printByHtml($('#myModal .modal-body .prevViewDiv'));
                            //直接打印（ print2 直接打印 ）
                            hiprint.print({templates: [{template: hiprintTemplate_index, data: index, options: {}}, {template: hiprintTemplate_content, data: itemList}]}, function (data) {
                                console.log('success')
                            });
                        })
                    }
                })
            });

            //打印
            $('#lr_print').on('click', function () {
                if (!$.isArray(kjkm) || kjkm.length == 0) {
                    learun.alert.warning('请选择科目！');
                    return;
                }
                learun.loading(true, '正在获取数据');

                learun.httpAsync2('GET', config.base_server() + 'reports/slmxzbook?access_token=' + config.getToken().access_token, params, function (res) {

                    learun.loading(false);
                    if (res.resp_code == 200) {
                        var index = {};
                        index.list = res.data.index;

                        var itemList = [];
                        for (var i = 0; i < res.data.content.length; i++) {
                            for (var j = 0; j < res.data.content[i].pzflList.length; j++) {
                                res.data.content[i].pzflList[j].j = $.formatMoney(res.data.content[i].pzflList[j].j, 2);
                                res.data.content[i].pzflList[j].d = $.formatMoney(res.data.content[i].pzflList[j].d, 2);
                                res.data.content[i].pzflList[j].ye = $.formatMoney(res.data.content[i].pzflList[j].ye, 2);
                            }
                            itemList.push(res.data.content[i]);
                        }

                        //直接打印（ print2 直接打印 ）
                        hiprint.print2({templates: [{template: hiprintTemplate_index, data: index, options: {}}, {template: hiprintTemplate_content, data: itemList}]}, function (data) {
                            console.log('success')
                        });
                    }
                })
            });

            //导出excel
            $('#lr_export_excel').on('click', function () {
                if (!$.isArray(kjkm) || kjkm.length == 0) {
                    learun.alert.warning('请选择科目！');
                    return;
                }
                if (params.companyId == undefined) {
                    learun.alert.warning('请先查询要导出的数据！');
                    return;
                }
                params.access_token = config.getToken().access_token;

                learun.download({
                    url: config.base_server() + 'reports/slmxzbook/excel',
                    param: params
                });
            });
            //导出pdf
            $('#lr_export_pdf').on('click', function () {
                if (!$.isArray(kjkm) || kjkm.length == 0) {
                    learun.alert.warning('请选择科目！');
                    return;
                }
                if (params.companyId == undefined) {
                    learun.alert.warning('请先查询要导出的数据！');
                    return;
                }
                params.access_token = config.getToken().access_token;

                learun.download({
                    url: config.base_server() + 'reports/slmxzbook/pdf',
                    param: params
                });
            });
            //导出无目录pdf
            $('#lr_export_pdf2').on('click', function () {
                if (!$.isArray(kjkm) || kjkm.length == 0) {
                    learun.alert.warning('请选择科目！');
                    return;
                }
                if (params.companyId == undefined) {
                    learun.alert.warning('请先查询要导出的数据！');
                    return;
                }
                params.access_token = config.getToken().access_token;

                learun.download({
                    url: config.base_server() + 'reports/slmxzbook/pdf2',
                    param: params
                });
            });
        },
        initGrid: function () {

        },
        search: function (param) {
            param = param || {};
            var pzrqStart = $("#pzrqStart").val();
            var pzrqEnd = $("#pzrqEnd").val();
            param.companyId = companyId;
            param.ztId = ztId;
            param.kjnd = kjnd;
            param.pzrqStart = pzrqStart;
            param.pzrqEnd = pzrqEnd;
            if ($.isArray(kjkm)&&kjkm.length > 0) {
                param.kjkmCodes = kjkm.join();
            } else {
                learun.alert.warning('请选择科目！');
                return;
            }

            param.kjkmCodes = kjkm.value;

            var formData = $('.lr-query-formcontent').lrGetFormData();

            param.ajEnable = formData.ajEnable;
            param.pjhEnable = formData.pjhEnable;
            param.wldxEnable = formData.wldxEnable;
            param.bmEnable = formData.bmEnable;
            param.xmEnable = formData.xmEnable;
            if ($.isArray(kjkm)) {
                param.kjkmCodes = kjkm.join();
            }

            params = param;

            if (!$.isArray(kjkm) || kjkm.length == 0) {
                learun.alert.warning('请选择科目！');
                return;
            }
            learun.loading(true, '正在获取数据');

            learun.httpAsync2('GET', config.base_server() + 'reports/slmxzbook?access_token=' + config.getToken().access_token, params, function (res) {
                learun.loading(false);
                if (res.resp_code == 200) {
                    var indexSize = 40;
                    var pzflSize = 37;
                    var index = {};
                    index.list = res.data.index.splice(0,indexSize);
                    if(res.data.content.length<=indexSize){
                        indexSize=res.data.content.length;
                    }
                    var itemList = [];
                    for (var i = 0; i < indexSize; i++) {
                        if(res.data.content[i].pzflList.length < pzflSize){
                            pzflSize = res.data.content[i].pzflList.length;
                        }
                        for (var j = 0; j < pzflSize; j++) {
                            res.data.content[i].pzflList[j].j = $.formatMoney(res.data.content[i].pzflList[j].j, 2);
                            res.data.content[i].pzflList[j].d = $.formatMoney(res.data.content[i].pzflList[j].d, 2);
                            res.data.content[i].pzflList[j].ye = $.formatMoney(res.data.content[i].pzflList[j].ye, 2);
                        }
                        //只预览37条记录
                        res.data.content[i].pzflList = res.data.content[i].pzflList.splice(0,pzflSize);
                        itemList.push(res.data.content[i]);
                    }

                    //多模板打印预览
                    $('.prevViewDiv2').html(hiprint.getHtml({templates: [{template: hiprintTemplate_index, data: index, options: {}}, {template: hiprintTemplate_content, data: itemList}]}));
                }
            })

            $("#pzrq_title").html(pzrqStart.substring(0, 10) + "至" + pzrqEnd.substring(0, 10));
            // $("#kjkm_title").html(kjkm.text);
        },

        initPrintTemplete: function () {
            learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', "&companyId=" + companyId + '&ztId=' + ztId + '&code=kmslzzb', function (res) {
                if (res.resp_code == 200) {
                    hiprintTemplate_content = new hiprint.PrintTemplate({
                        template: JSON.parse(res.data.templete),
                        paginationContainer: '.hiprint-printPagination'
                    });

                    learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', "&companyId=" + companyId + '&ztId=' + ztId + '&code=zbindex', function (res) {
                        if (res.resp_code == 200) {
                            hiprintTemplate_index = new hiprint.PrintTemplate({
                                template: JSON.parse(res.data.templete),
                                paginationContainer: '.hiprint-printPagination'
                            });
                        }
                    });
                }
            });
        },

        createPrintHtml: function (printers) {
            var ul = $('<select></select>');
            $.each(printers, function (index, printer) {
                ul.append('<option value="' + printer.name + '" ' + (printer.isDefault ? 'selected' : '') + '>' + printer.name + '</option>');
            })
            return ul;
        },
    };

    // 保存数据后回调刷新
    refreshGirdData = function () {
        page.search();
    };

    page.init();
}


